using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using RdfMusic;
using SemWeb;

namespace Mp3ToRdf
{
    public partial class Form2 : Form
    {
        private readonly MusicStore store;

        public Form2(MusicStore store)
        {
            this.store = store;
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            SetupFilterLists();
        }

        private void SetupFilterLists()
        {
            lbGenres.DataSource = new List<string>(GetGenresDistinct());
            lbGenres.DataSource = new List<string>(GetGenresDistinct());
            lbArtists.DataSource = new List<string>(GetArtistsDistinct());
            lbYears.DataSource = new List<string>(GetYearsDistinct());
        }

        private IEnumerable<string> GetYearsDistinct()
        {
            return GetByPredicate(MusicConstants.Year);
        }

        private IEnumerable<string> GetArtistsDistinct()
        {
            return GetByPredicate(MusicConstants.ArtistName);
        }

        private IEnumerable<string> GetGenresDistinct()
        {
            return GetByPredicate(MusicConstants.GenreName);
        }

        private IEnumerable<string> GetByPredicate(Entity predicate)
        {
            Resource[] ra = store.TripleStore.SelectObjects(null, predicate);
            Dictionary<string, string> ht = new Dictionary<string, string>(); 
            foreach (Resource statement in ra)
            {
                string gn = GetValue(statement);
                if (!ht.ContainsKey(gn))
                {
                    ht[gn] = gn;
                    yield return gn;
                }
            }
        }

        private static string GetValue(Resource statement)
        {
            Literal lit = statement as Literal;
            if (lit != null)
                return lit.Value;
            return statement.Uri;
        }

        private void Search(object sender, EventArgs e)
        {
            IList<string> genres = GetSelectedItemsAsStringList(lbGenres);
            IList<string> artists = GetSelectedItemsAsStringList(lbArtists);
            IList<string> years = GetSelectedItemsAsStringList(lbYears);

            SearchResults sr = new SearchResults();
            sr.Genres = genres;
            sr.Artists = artists;
            sr.Years = years;
            sr.Store = store;
            sr.Show(this);
        }

        private IList<string> GetSelectedItemsAsStringList(ListBox lb)
        {
            List<string> result = new List<string>();
            foreach (object obj in lb.SelectedItems)
            {
                result.Add(obj.ToString().Trim());
            }
            return result;
        }
    }
}